//
//  ScheduleMeetingViewController.m
//  Conference
//
//  Created by Xiang He on 12-11-15.
//  Copyright (c) 2012年 __MyCompanyName__. All rights reserved.
//会议日程

#import "ScheduleMeetingViewController.h"
#import "Globals.h"
#import "Constant.h"
#import "NetContant.h"
#import "ScheduleCellController.h"
#import "WebData.h"
#import "ScheduleDetailData.h"
@interface ScheduleMeetingViewController ()

@end

@implementation ScheduleMeetingViewController
@synthesize table;
@synthesize scrollView;
@synthesize arrayOfData;
@synthesize amRet;
@synthesize pmRet;
@synthesize nightRet;
@synthesize floatX;
@synthesize scrollWidth;
@synthesize selectDate;
@synthesize hashMap;
@synthesize arrayOfTableData;
@synthesize scrollCenter;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
      [super viewDidLoad];
    self.floatX=10;
    [self.scrollView setShowsHorizontalScrollIndicator:NO];
    self.scrollCenter=CGPointMake(160, 35);
    self.table.separatorStyle=NO;
    self.amRet=@"";
    self.pmRet=@"";
    self.nightRet=@"";
    self.arrayOfData=[NSMutableArray arrayWithCapacity:0];
    self.arrayOfTableData=[NSMutableArray arrayWithCapacity:0];
    self.hashMap=[NSMutableDictionary dictionaryWithCapacity:0];
    [self loadingData:@""];
  
    // Do any additional setup after loading the view from its nib.
}

-(void)addDateButton:(NSString *)date{
    
    UIButton *btn=[UIButton buttonWithType:UIButtonTypeCustom];
    btn.frame=CGRectMake(self.floatX, 10, 85, 25);
    btn.titleLabel.font = [UIFont systemFontOfSize: 12.0];
    UIImage *nromalBg=[UIImage imageNamed:@"date_label_normal@2x.png"];
    UIImage *pressedBg=[UIImage imageNamed:@"date_lable_pressed@2x.png"];
    [btn setBackgroundImage:nromalBg forState:UIControlStateNormal];//设置正常状态
    [btn setBackgroundImage:pressedBg forState:UIControlStateHighlighted];//设置选择状态
    [btn setTitle:date forState:UIControlStateNormal];
    [btn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [btn addTarget:self action:@selector(selectDateAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.scrollView addSubview:btn];
    self.floatX=self.floatX+90;
}

-(void)selectDateAction:(id)sender{
    UIButton *btn = (UIButton *)sender;
    
    CGPoint btnCenter= btn.center;
//    NSLog(@"btn.%f,btn.%f",btnCenter.x,btnCenter.y);
    float currentX=self.scrollCenter.x-btnCenter.x;
//    NSLog(@"%f",currentX);
    if(currentX>0){
      [self.scrollView setContentMode:UIViewContentModeTopRight];
    [self.scrollView setContentOffset:CGPointMake(-currentX, 0)animated:YES];
    }else if (currentX<0) {
          [self.scrollView setContentMode:UIViewContentModeTopLeft];
         [self.scrollView setContentOffset:CGPointMake(currentX, 0)animated:YES];
    }else {
    }
    
    
    self.selectDate=btn.titleLabel.text;
    //先读取map
    NSString *str=[self.hashMap objectForKey:self.selectDate];
    if(nil!=str){
        [self.arrayOfTableData removeAllObjects];
        
        NSArray *item_table=[str componentsSeparatedByString:[NetContant getInstance].TABLES_SPLIT_FLAG];
        if (item_table==nil  || [item_table objectAtIndex:0]==nil) {
            return;
        }
        NSArray *item=[[item_table objectAtIndex:0] componentsSeparatedByString:[NetContant getInstance].RECORDS_SPLIT_FLAG];
        for(int i=0;i<[item count];i++){
            NSString *curr=[item objectAtIndex:i];
            if (![curr isEqualToString:@""]) {
                NSArray *details=[curr componentsSeparatedByString:@","];
                if (nil==details||[details count]<3)
                    continue;
                [self parseData:curr info:details];
            }
        }
                    [self.table reloadData];
    }else 
        [self loadingData:self.selectDate]; 
    
    
   
    
}



-(void)loadingData:(NSString *)date{
    
    NSThread *thread=[[[NSThread alloc] initWithTarget:self selector:@selector(run:) object:date] autorelease];
    [thread start];
    
}

-(void)run:(NSString*)date{
    NSAutoreleasePool *pool=[[NSAutoreleasePool alloc] init];
    NSString *sRet;
    if ([@"" isEqualToString:date]) {
        sRet=[[WebData getInstance]getMemberScheduleDate];
        [self performSelectorOnMainThread:@selector(onPostExecute:) withObject:sRet waitUntilDone:YES];
    }else {
        sRet=[[WebData getInstance]getMemberSchedule:date];
        [self performSelectorOnMainThread:@selector(onPostExecutes:) withObject:sRet waitUntilDone:YES];
    }
    
	[pool release];
    
}
-(void)onPostExecute:(NSString *)sRet{
    if ([sRet isEqualToString:[[NetContant getInstance] NET_CONNECT_FALSE]]) {
        
        //[[Globals getInstance] showAlertView:[[Constant getInstance] net_error]];
        
    }else if([sRet isEqualToString:[[NetContant getInstance] NETWORK_DB_EXCEPTION]]){
    
    
    }
    else if([sRet isEqualToString:[[NetContant getInstance] NETWORK_RECORD_ISEMPTY]]){
        
       // [[Globals getInstance] showAlertView:[[Constant getInstance] account_error]];
    }else {
        @try {
            [self doNetGetDateRet:sRet];
            [self doNetGetDateInfo];
        }
        @catch (NSException *exception) {
            
        }
    }
    
}

-(void)onPostExecutes:(NSString *)sRet{
    if ([sRet isEqualToString:[[NetContant getInstance] NET_CONNECT_FALSE]]) {
        [[Globals getInstance] showAlertView:[[Constant getInstance] net_error]];
    }else if([sRet isEqualToString:[[NetContant getInstance] NETWORK_RECORD_ISEMPTY]]){
        
        [[Globals getInstance] showAlertView:[[Constant getInstance] account_error]];
    }else {
        @try {
          [self doNetRet:sRet];
        [self doNetInfo];
        }
        @catch (NSException *exception) {
            
        }
    }
    
}

-(void)doNetGetDateRet:(NSString*)sRet{
    NSArray *record=[sRet componentsSeparatedByString:[NetContant getInstance].RECORDS_SPLIT_FLAG];
    if(nil!=record){
        [self.arrayOfData removeAllObjects];
        for(int i=0;i<[record count];i++){
            NSString *sDate=[record objectAtIndex:i];
        if(![@"" isEqualToString:sDate]&&nil!=sDate)
            [self.arrayOfData addObject:sDate];
        }
    
    }

}
-(void)doNetRet:(NSString *)sRet{
   
    NSArray *item_table=[sRet componentsSeparatedByString:[NetContant getInstance].TABLES_SPLIT_FLAG];
    if (item_table==nil  || [item_table objectAtIndex:0]==nil) {
        return;
    }

    NSArray *record=[[item_table objectAtIndex:0] componentsSeparatedByString:[[NetContant getInstance] RECORDS_SPLIT_FLAG]];
    int size=[record count];
            if(nil==record||size==0){
                return;
            }
    [self.arrayOfTableData removeAllObjects];
    for (int i=0; i<size; i++) {
        NSString *curr=[record objectAtIndex:i];
        if (![curr isEqualToString:@""]) {
            NSArray *details=[curr componentsSeparatedByString:@","];
            if (nil==details||[details count]<3)
                continue;
            [self parseData:curr info:details];
        }
    }
    //缓存
    if(nil==[self.hashMap objectForKey:self.selectDate]){
    NSDictionary *map = [NSDictionary dictionaryWithObjectsAndKeys:[NSString stringWithFormat:@"%@|%@|%@",amRet,pmRet,nightRet],self.selectDate,nil];
        [self.hashMap addEntriesFromDictionary:map];
    }
}

-(void)parseData:(NSString *)curr info:(NSArray*)details{
    if([curr hasPrefix:@"上午"]){
        NSArray *am=[curr componentsSeparatedByString:@";"];
        
        for(int j=0;j<[am count];j++){     
            ScheduleDetailData *amData=[[ScheduleDetailData alloc]init];
            NSArray *amDetail=[[am objectAtIndex:j]  componentsSeparatedByString:@","]; 
            amData.currType=@"am";
            amData.date=[amDetail objectAtIndex:0];
            amData.title=[amDetail objectAtIndex:1];
            amData.place=[amDetail objectAtIndex:2];
            [self.arrayOfTableData addObject:amData];
            [amData release];
            
            
        }self.amRet=curr;
        
    }
    else if ([curr hasPrefix:@"下午"]){
        
        NSArray *pm=[curr componentsSeparatedByString:@";"];
        
        for(int j=0;j<[pm count];j++){     
        ScheduleDetailData *pmData=[[ScheduleDetailData alloc]init];
        NSArray *pmDetail=[[pm objectAtIndex:j]  componentsSeparatedByString:@","]; 
        pmData.currType=@"pm";
        pmData.date=[pmDetail objectAtIndex:0];
        pmData.title=[pmDetail objectAtIndex:1];
        pmData.place=[pmDetail objectAtIndex:2];
        [self.arrayOfTableData addObject:pmData];
        [pmData release];
        }
        self.pmRet=curr;
    }
    else if([curr hasPrefix:@"晚上"]){
        
        NSArray *nm=[curr componentsSeparatedByString:@";"];
        
        for(int j=0;j<[nm count];j++){   
        ScheduleDetailData *nightData=[[ScheduleDetailData alloc]init];
        NSArray *nmDetail=[[nm objectAtIndex:j]  componentsSeparatedByString:@","]; 

        nightData.currType=@"night";
        nightData.date=[nmDetail objectAtIndex:0];
        nightData.title=[nmDetail objectAtIndex:1];
        nightData.place=[nmDetail objectAtIndex:2];
        [self.arrayOfTableData addObject:nightData];
        [nightData release];
        }
        self.nightRet=curr;
    }
}
-(void)doNetGetDateInfo{
    
    int size=[self.arrayOfData count];
    self.scrollWidth=size*90+20;
    if (self.scrollWidth<=320) {
        self.scrollWidth=320;
    }
    [self.scrollView setContentSize:CGSizeMake(self.scrollWidth, 50)];
    for(int i=0;i<size;i++){
        [self addDateButton:[arrayOfData objectAtIndex:i]];
    }
    
    
}
-(void)doNetInfo{
    [self.table reloadData];

}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
      UITableViewCell *cell = [self tableView:tableView cellForRowAtIndexPath:indexPath];
       return cell.frame.size.height;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return [self.arrayOfTableData count];
}
-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *scheduleCell=@"scheduleCell";
    ScheduleCellController *cell=(ScheduleCellController *)[tableView dequeueReusableCellWithIdentifier:scheduleCell];
    if(cell ==nil){
		NSArray *array = [[NSBundle mainBundle] loadNibNamed:@"ScheduleCellController" owner:self options:nil];   
		for (id oneObject in array) {
			if ([oneObject isKindOfClass:[ScheduleCellController class]]) {
				cell=oneObject;
				break;
			}
		}

          cell.backgroundView=[[[UIImageView alloc] initWithImage:[[UIImage imageNamed:@"msg_bg_normal.png"] stretchableImageWithLeftCapWidth:20 topCapHeight:20]] autorelease];
        
           cell.selectedBackgroundView=[[[UIImageView alloc] initWithImage:[[UIImage imageNamed:@"msg_bg_pressed.png"] stretchableImageWithLeftCapWidth:20 topCapHeight:20]] autorelease];
    }
//    NSString *curr=[self.arrayOfTableData objectAtIndex:[indexPath row]];
//     NSArray *netRet=[curr componentsSeparatedByString:[[NetContant getInstance] IMGURL_SPLIT_FLAG]];
//    
//    if(nil!=netRet||[netRet count]>=3){
//    UIImage *img=nil;
//    if([curr hasPrefix:@"上午"])
//        img=[UIImage imageNamed:@"AM.png"];
//    else if ([curr hasPrefix:@"下午"])
//        img=[UIImage imageNamed:@"PM.png"];
//    else if([curr hasPrefix:@"晚上"])
//        img=[UIImage imageNamed:@"night.png"];
//
//    cell.lab_title.text=[netRet objectAtIndex:0];
//    cell.lab_time.text=[netRet objectAtIndex:1];
//    cell.lab_address.text=[netRet objectAtIndex:2];
//    [cell.img_time setImage:img];}

    ScheduleDetailData *data=[self.arrayOfTableData objectAtIndex:[indexPath row]];
    NSString *type=data.currType;
    UIImage *img=nil;
    if ([type isEqualToString:@"am"]) {
        img=[UIImage imageNamed:@"AM.png"];
    }else if([type isEqualToString:@"pm"]){
     img=[UIImage imageNamed:@"PM.png"];}else{
     img=[UIImage imageNamed:@"night.png"];}
    [cell.img_time setImage:img];
    cell.lab_title.text=data.title;
    cell.lab_time.text=data.date;
    cell.lab_address.text=data.place;
    return cell;
}
- (void)viewDidUnload
{
    [self setArrayOfTableData:nil];
    [self setSelectDate:nil];
    [self setHashMap:nil];
    [self setAmRet:nil];
    [self setPmRet:nil];
    [self setNightRet:nil];
    [self setArrayOfData:nil];
    [self setScrollView:nil];
    [self setTable:nil];
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

-(void)dealloc{
    [arrayOfTableData release];
    [selectDate release];
    [hashMap release];
    [amRet release];
    [pmRet release];
    [nightRet release];
    [arrayOfData release];
    [scrollView release];
    [table release];
    [super dealloc];
}

@end
